package com.raft.framework;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.multidex.MultiDex;
import com.blankj.utilcode.util.ProcessUtils;
import com.blankj.utilcode.util.Utils;
import com.raft.framework.internal.CrashReportingTree;
import io.reactivex.Scheduler;
import io.reactivex.android.plugins.RxAndroidPlugins;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import timber.log.Timber;

import java.util.concurrent.Callable;

public class BaseAppContext extends Application implements Application.ActivityLifecycleCallbacks {


    @SuppressLint("StaticFieldLeak")
    private static BaseAppContext sContext;

    @Override
    public void onCreate() {
        super.onCreate();
        sContext = this;
        Utils.init(this);

        if(isDebug()){
            Timber.plant(new Timber.DebugTree());
        }else{
            Timber.plant(new CrashReportingTree());
        }

        initAllProcess();

        if (ProcessUtils.isMainProcess()) {
            initMainProcess();
        }
    }

    public boolean isDebug(){
        return true;
    }

    protected void initAllProcess() {

    }


    protected void initMainProcess() {
        registerActivityLifecycleCallbacks(this);

        final Scheduler asyncMainThreadScheduler = AndroidSchedulers.from(Looper.getMainLooper(), true);
        RxAndroidPlugins.setInitMainThreadSchedulerHandler(
                new Function<Callable<Scheduler>, Scheduler>() {
                    @Override
                    public Scheduler apply(Callable<Scheduler> schedulerCallable) throws Exception {
                        return asyncMainThreadScheduler;
                    }
                });
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);

        MultiDex.install(this);
    }


    public static @NonNull
    Context getContext() {
        return sContext;
    }

    public static boolean debug(){
        return sContext.isDebug();
    }




    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }
}
